package test.day01;

import java.util.HashMap;
import java.util.Map;

public class TwoSum {
	// 在数组中找到 2 个数之和等于给定值的数字，结果返回 2 个数字在数组中的下标
	// Given nums = [2, 7, 11, 15], target = 9,
	// Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]

	public static void main(String[] args) {
		int[] nums = new int []{2, 7, 11, 15, 18};
		int[] result = twoSum(nums, 18);
		System.out.println(result[0] + "====" + result[1]);
	}


	public static int[] twoSum(int[] nums, int target) {
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			map.put(nums[i], i);
		}
		for (int j = 0; j < nums.length; j++) {
			// 包含另一个非本身的元素和等于target
			int other = target - nums[j];
			if (map.containsKey(other) && (map.get(other) != j)) {
				return new int[] {j, map.get(other)};
			}
		}
		return new int[]{-1, -1};
	}
}
